<script setup>
import { ref, onMounted } from 'vue';
import { saveAs } from 'file-saver';

// 引用FileSaver库用于文件导出
// 数据状态
const texts = ref([]);
const currentText = ref({ id: '', english: '', chinese: '' });
const isLoading = ref(false);
const error = ref('');

// 上传文件处理
const handleFileUpload = (event) => {
  const file = event.target.files[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = (e) => {
    try {
      const content = e.target.result;
      const lines = content.split('\n');
      const newTexts = [];

      for (let i = 0; i < lines.length; i++) {
        const line = lines[i].trim();
        if (!line) continue;

        // 假设文件格式为: 英文原文\n中文翻译\n...
        let translation = '';
        if (i + 1 < lines.length) {
          const nextLine = lines[i + 1].trim();
          if (nextLine && !nextLine.startsWith('[') && !/^\d+$/.test(nextLine)) {
            translation = nextLine;
            i++;
          }
        }

        newTexts.push({
          id: Date.now() + i,
          english: line,
          chinese: translation
        });
      }

      // 合并现有数据和新数据
      const existingIds = new Set(texts.value.map(t => t.id));
      newTexts.forEach(text => {
        if (!existingIds.has(text.id)) {
          texts.value.push(text);
        }
      });

      // 保存到服务器
      saveTexts();
      error.value = '';
    } catch (err) {
      error.value = `文件解析错误: ${err.message}`;
    }
  };
  reader.readAsText(file);
};

// 从服务器获取文本数据
const fetchTexts = async () => {
  isLoading.value = true;
  try {
    const response = await fetch('http://localhost:5000/api/texts');
    if (!response.ok) throw new Error('无法获取数据');
    texts.value = await response.json();
    error.value = '';
  } catch (err) {
    error.value = `获取数据失败: ${err.message}`;
  } finally {
    isLoading.value = false;
  }
};

// 保存文本数据到服务器
const saveTexts = async () => {
  try {
    for (const text of texts.value) {
      const response = await fetch('http://localhost:5000/api/texts', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(text)
      });
      if (!response.ok) throw new Error('保存数据失败');
    }
    error.value = '';
  } catch (err) {
    error.value = `保存数据失败: ${err.message}`;
  }
};

// 导出数据
const exportData = async () => {
  try {
    const response = await fetch('http://localhost:5000/api/export');
    if (!response.ok) throw new Error('导出数据失败');
    const blob = await response.blob();
    saveAs(blob, 'translation_export.json');
    error.value = '';
  } catch (err) {
    error.value = `导出数据失败: ${err.message}`;
  }
};

// 监听翻译输入变化
const handleTranslationChange = (id, value) => {
  const text = texts.value.find(t => t.id === id);
  if (text) {
    text.chinese = value;
    // 实时保存
    saveTexts();
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchTexts();
});
</script>

<template>
  <div class="translation-container">
    <h1>英语翻译练习</h1>

    <div class="controls">
      <div class="upload-area">
        <input type="file" id="file-upload" @change="handleFileUpload" class="file-input" />
        <label for="file-upload" class="upload-btn">上传文件</label>
      </div>
      <button @click="exportData" class="export-btn">导出翻译</button>
    </div>

    <div v-if="error" class="error-message">{{ error }}</div>

    <div v-if="isLoading" class="loading">加载中...</div>

    <div v-else-if="texts.length === 0" class="empty-state">
      <p>暂无翻译文本，请上传文件导入英文原文</p>
    </div>

    <div v-else class="translation-list">
      <div v-for="text in texts" :key="text.id" class="translation-item">
        <div class="english-text">{{ text.english }}</div>
        <textarea
          v-model="text.chinese"
          @input="handleTranslationChange(text.id, text.chinese)"
          class="chinese-text"
          :style="{ height: `${Math.max(40, text.chinese.split('\n').length * 20)}px` }"
          placeholder="请输入中文翻译..."
        ></textarea>
      </div>
    </div>
  </div>
</template>

<style scoped>
.translation-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background-color: #f8f9fa; /* 护眼浅色背景 */
  min-height: 100vh;
}

h1 {
  color: #333;
  text-align: center;
  margin-bottom: 30px;
}

.controls {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.upload-area {
  position: relative;
}

.file-input {
  position: absolute;
  opacity: 0;
  width: 0.1px;
  height: 0.1px;
}

.upload-btn, .export-btn {
  background-color: #42b983;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.upload-btn:hover, .export-btn:hover {
  background-color: #3aa876;
}

.error-message {
  color: #e74c3c;
  background-color: #fadbd8;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.loading {
  text-align: center;
  padding: 20px;
  color: #666;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #666;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.translation-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.translation-item {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s, box-shadow 0.2s;
}

.translation-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.english-text {
  font-family: 'Times New Roman', Times, serif;
  font-size: 18px;
  line-height: 1.6;
  color: #333;
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.chinese-text {
  width: 100%;
  padding: 10px;
  font-size: 16px;
  line-height: 1.6;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: vertical;
  min-height: 40px;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
  color: #333;
  box-sizing: border-box;
}

.chinese-text:focus {
  outline: none;
  border-color: #42b983;
  box-shadow: 0 0 0 2px rgba(66, 185, 131, 0.2);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .translation-container {
    padding: 15px;
  }

  h1 {
    font-size: 24px;
  }

  .english-text {
    font-size: 16px;
  }

  .chinese-text {
    font-size: 14px;
  }
}
</style>